package com.jiankangjin.weixinchannel.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jiankangjin.weixinchannel.config.WeixinConfig;

public class ResponseHandler {
	/** 返回的参数 */
	public SortedMap<String, String> paramsMap;
	/** 返回的XML参数 */
	public SortedMap<String, String> xmlMap;

	private HttpServletRequest request;
	private HttpServletResponse response;
	private String uriEncoding;

	public ResponseHandler() {
		
	}
	/**
	 * 构造方法
	 */
	public ResponseHandler(HttpServletRequest request,
			HttpServletResponse response) {
		// 初始化参数
		this.request = request;
		this.response = response;
		this.uriEncoding = "";
		// 返回的参数
		this.paramsMap = new TreeMap<String, String>();
		Map<?, ?> m = this.request.getParameterMap();
		Iterator<?> it = m.keySet().iterator();
		while (it.hasNext()) {
			String k = (String) it.next();
			String v = ((String[]) m.get(k))[0];
			this.paramsMap.put(k, v);
		}
		// 返回的XML参数
		String xmlContext = getStr(request);
		if (StringUtil.isNotEmpty(xmlContext)) {
			this.xmlMap = doParse(xmlContext);
		}
	}

	/**
	 * 从request中取出XML的String
	 */
	private String getStr(HttpServletRequest request) {
		try {
			InputStream in = request.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(in);
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				sb.append(line);
			}
			inputStreamReader.close();
			in.close();
			return sb.toString();
		} catch (Exception e) {
		}
		return "";
	}

	/**
	 * 把XML的String转为Map对象
	 */
	public SortedMap<String, String> doParse(String xmlContent) {
		SortedMap<String, String> map = new TreeMap<String, String>();
		try {
			Map<?, ?> m = XMLUtil.doXMLParse(xmlContent);
			Iterator<?> it = m.keySet().iterator();
			while (it.hasNext()) {
				String k = (String) it.next();
				String v = (String) m.get(k);
				map.put(k, v);
			}
		} catch (Exception e) {
		}
		return map;
	}

	/**
	 * 是否财付通签名,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 */
	public boolean isValidSign() {
		StringBuffer sb = new StringBuffer();
		Set<Entry<String, String>> es = this.paramsMap.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Entry<?, ?> entry = (Entry<?, ?>) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (!"sign".equals(k) && null != v && !"".equals(v)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + WeixinConfig.PARTNER_KEY);
		String enc = TenpayUtil.getCharacterEncoding(this.request, this.response);
		String sign = MD5Util.MD5Encode(sb.toString(), enc).toUpperCase();
		String ValidSign = this.paramsMap.get(("sign")).toUpperCase();
		return ValidSign.equals(sign);
	}

	/**
	 * 判断微信PostData的签名
	 */
	public boolean isWXsign() {
		this.xmlMap.put("appkey", WeixinConfig.APP_KEY);
		SortedMap<String, String> sm = new TreeMap<String, String>();
		for (String key : this.xmlMap.keySet()) {
			if (key != "SignMethod" && key != "AppSignature") {
				sm.put(key.toLowerCase(), this.xmlMap.get(key));
			}
		}
		StringBuffer sb = new StringBuffer();
		Set<Entry<String, String>> es = sm.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = (Entry<String, String>) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (k != "SignMethod" && k != "AppSignature") {
				sb.append(k + "=" + v + "&");
			}
		}
		String str = sb.toString();
		str = str.substring(0, str.lastIndexOf("&"));
		return Sha1Util.getSha1(str).equals(this.xmlMap.get("AppSignature"));
	}

	/**
	 * 判断微信PostData 维权信息的签名
	 */
	public boolean isWXPayFeedbackSign() {
		SortedMap<String, String> sm = new TreeMap<String, String>();
		sm.put("appid", this.xmlMap.get("AppId"));
		sm.put("timestamp", this.xmlMap.get("TimeStamp"));
		sm.put("openid", this.xmlMap.get("OpenId"));
		sm.put("appkey", WeixinConfig.APP_KEY);
		StringBuffer sb = new StringBuffer();
		Set<Entry<String, String>> es = sm.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = (Entry<String, String>) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (k != "SignMethod" && k != "AppSignature") {
				sb.append(k + "=" + v + "&");
			}
		}
		String str = sb.toString();
		str = str.substring(0, str.lastIndexOf("&"));
		return Sha1Util.getSha1(str).equals(this.xmlMap.get("AppSignature"));
	}
	
	/**
	 * 获取uri编码
	 */
	public String getUriEncoding() {
		return uriEncoding;
	}

	/**
	 * 设置uri编码
	 */
	public void setUriEncoding(String uriEncoding)
			throws UnsupportedEncodingException {
		if (!"".equals(uriEncoding.trim())) {
			this.uriEncoding = uriEncoding;
			// 编码转换
			String enc = TenpayUtil.getCharacterEncoding(request, response);
			Iterator<String> it = this.paramsMap.keySet().iterator();
			while (it.hasNext()) {
				String k = (String) it.next();
				String v = this.paramsMap.get(k);
				v = new String(v.getBytes(uriEncoding.trim()), enc);
				this.paramsMap.put(k, v);
			}
		}
	}
}